package com.firesrc.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jodd.util.StringUtil;

import com.firesrc.bean.ProcessorBean;
import com.firesrc.service.server.ProcessDataService;
import com.firesrc.service.server.ProcessDataServiceImpl;
import com.firesrc.util.EncryptUtil;
import com.firesrc.util.SystemConfigConstant;

/**
 * 接受所有c端数据的处理类
 */
public class ProcessData extends HttpServlet {
  private static final long serialVersionUID = 1L;

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doPost(request, response);
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/*");
    final ProcessorBean processorBean = getProcessorBean(request);
    if (processorBean == null) {
      response.getWriter().print("");
      return;
    }
    ProcessDataService service = new ProcessDataServiceImpl();
    String handle = service.handle(processorBean);
    System.out.println("接收到数据类型" + processorBean.getType());
    response.getWriter().print(handle);
  }

  public ProcessorBean getProcessorBean(HttpServletRequest request) {
    EncryptUtil encryptUtil = new EncryptUtil("woaiwojia");
    String type = request.getParameter(SystemConfigConstant.TRAFFER_TYPE_FLAG);
    if (StringUtil.isEmpty(type)) {
      return null;
    }
    String expandData = "";
    String decryptType = "";
    try {
      decryptType = encryptUtil.decrypt(type);
      if (StringUtil.isEmpty(decryptType)) {
        return null;
      }

      String data = request.getParameter(SystemConfigConstant.TRAFFER_DATA_FLAG);
      expandData = encryptUtil.decrypt(data);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
    ProcessorBean processor = new ProcessorBean();
    processor.setType(decryptType);
    processor.setData(expandData);
    return processor;
  }
}
